import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/music_provider.dart';
import '../models/song.dart';
import '../utils/image_cache_service.dart';
import 'package:palette_generator/palette_generator.dart';

class MusicPlayerPage extends StatefulWidget {
  const MusicPlayerPage({Key? key}) : super(key: key);

  @override
  State<MusicPlayerPage> createState() => _MusicPlayerPageState();
}

class _MusicPlayerPageState extends State<MusicPlayerPage> with TickerProviderStateMixin {
  final ImageCacheService _imageCacheService = ImageCacheService();
  late AnimationController _rotationController;
  Color? _dominantColor;
  String? _currentSongId; // 用于跟踪当前歌曲，避免重复提取颜色

  @override
  void initState() {
    super.initState();
    _rotationController = AnimationController(
      duration: const Duration(seconds: 10),
      vsync: this,
    );
  }

  @override
  void dispose() {
    _rotationController.dispose();
    super.dispose();
  }

  Future<void> _updateDominantColor(ImageProvider imageProvider, String songId) async {
    try {
      final PaletteGenerator paletteGenerator = await PaletteGenerator.fromImageProvider(imageProvider);
      if (mounted && _currentSongId == songId) { // 确保还是同一首歌
        setState(() {
          _dominantColor = paletteGenerator.dominantColor?.color ?? Colors.black.withOpacity(0.3);
        });
      }
    } catch (e) {
      print('Error generating palette: $e');
      if (mounted && _currentSongId == songId) {
        setState(() {
          _dominantColor = Colors.black.withOpacity(0.3);
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MusicProvider>(
      builder: (context, musicProvider, child) {
        final song = musicProvider.currentSong;
        final songId = song?.path ?? '';
        
        // 检查是否有封面
        final albumArtProvider = _imageCacheService.getImageProvider(song?.albumArtUri);
        bool hasAlbumArt = albumArtProvider != null;
        
        // 如果歌曲发生了变化，重置颜色并重新提取
        if (_currentSongId != songId) {
          _currentSongId = songId;
          _dominantColor = null;
          if (hasAlbumArt) {
            _updateDominantColor(albumArtProvider!, songId);
          }
        }
        
        // 如果没有封面，清除主色调
        if (!hasAlbumArt && _dominantColor != null) {
          setState(() {
            _dominantColor = null;
          });
        }

        // 控制旋转动画
        if (musicProvider.isPlaying && hasAlbumArt) {
          _rotationController.repeat();
        } else {
          _rotationController.stop();
        }

        return Scaffold(
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: const AssetImage('img/音乐播放页-木子米.jpeg'),
                fit: BoxFit.cover,
              ),
            ),
            child: Stack(
              children: [
                // 半透明遮罩层（仅在有封面时显示）
                if (hasAlbumArt && _dominantColor != null)
                  Container(
                    color: _dominantColor!.withOpacity(0.6),
                  ),
                
                Column(
                  children: [
                    // 顶部导航栏
                    _buildTopBar(context, song),
                    
                    // 主要内容区域
                    Expanded(
                      child: Column(
                        children: [
                          // 中间的胶片装饰区域
                          if (hasAlbumArt)
                            _buildVinylRecord(albumArtProvider!),
                          
                          // 占位符，将卡片推到底部
                          const Spacer(),
                          
                          // 歌曲信息和进度条区域
                          _buildSongInfoAndProgress(musicProvider, song),
                          
                          // 控制按钮区域
                          _buildControlButtons(musicProvider),
                          
                          // 底部工具栏
                          _buildBottomToolbar(),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 胶片旋转装饰区域
  Widget _buildVinylRecord(ImageProvider albumArt) {
    return Container(
      margin: const EdgeInsets.only(top: 80),
      child: Stack(
        alignment: Alignment.center,
        children: [
          // 外圈胶片效果
          Container(
            width: 200,
            height: 200,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              gradient: RadialGradient(
                colors: [
                  Colors.black.withOpacity(0.3),
                  Colors.black.withOpacity(0.1),
                  Colors.transparent,
                ],
                stops: [0.7, 0.85, 1.0],
              ),
            ),
          ),
          
          // 旋转的封面
          RotationTransition(
            turns: _rotationController,
            child: Container(
              width: 160,
              height: 160,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image: albumArt,
                  fit: BoxFit.cover,
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    blurRadius: 20,
                    offset: const Offset(0, 10),
                  ),
                ],
              ),
            ),
          ),
          
          // 中心圆点
          Container(
            width: 20,
            height: 20,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.black.withOpacity(0.7),
              border: Border.all(
                color: Colors.white.withOpacity(0.5),
                width: 2,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 顶部导航栏
  Widget _buildTopBar(BuildContext context, Song? song) {
    return Container(
      height: 40,
      margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(216, 216, 216, 0.5), // paint_7:5536
      ),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.pop(context),
            child: Container(
              width: 36,
              height: 36,
              margin: const EdgeInsets.only(left: 10, top: 2),
              child: Icon(
                Icons.keyboard_arrow_down,
                color: const Color(0xFF000000), // paint_7:190
                size: 24,
              ),
            ),
          ),
          
          // 中间标题
          Expanded(
            child: Container(
              height: 40, // 与父容器高度一致
              alignment: Alignment.center, // 确保垂直居中
              child: Text(
                song?.name ?? '我喜欢的音乐',
                style: TextStyle(
                  color: const Color(0xFF3D3D3D), // paint_7:00
                  fontSize: 14,
                  fontFamily: 'Source Han Sans',
                  fontWeight: FontWeight.bold,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          
          // 分享按钮
          Container(
            width: 36,
            height: 36,
            margin: const EdgeInsets.only(right: 10, top: 2),
            child: Icon(
              Icons.share,
              color: const Color(0xFF000000), // paint_7:190
              size: 24,
            ),
          ),
        ],
      ),
    );
  }

  // 歌曲信息和进度条区域
  Widget _buildSongInfoAndProgress(MusicProvider musicProvider, Song? song) {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.symmetric(horizontal: 0), // 移除左右间距
      decoration: BoxDecoration(
        color: const Color.fromRGBO(255, 255, 255, 0.8), // paint_7:4191
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(8),
          topRight: Radius.circular(8),
        ),
      ),
      child: Column(
        children: [
          // 歌曲信息
          Container(
            padding: const EdgeInsets.all(14),
            child: Row(
              children: [
                // 歌曲名和歌手信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        song?.name ?? 'Lingo Starr：STRIKES BACK',
                        style: TextStyle(
                          color: const Color(0xFF3D3D3D), // paint_7:00
                          fontSize: 16,
                          fontFamily: 'Source Han Sans',
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          // 智能歌手名称组件
                          _buildArtistName(song?.artist ?? 'tobi lou'),
                          const SizedBox(width: 8),
                          // 关注按钮
                          Container(
                            height: 16,
                            padding: const EdgeInsets.symmetric(horizontal: 12),
                            decoration: BoxDecoration(
                              color: const Color(0xFFD8D8D8), // paint_7:11
                              borderRadius: BorderRadius.circular(30),
                            ),
                            child: Center(
                              child: Text(
                                '关注',
                                style: TextStyle(
                                  color: const Color(0xFF3D3D3D), // paint_7:00
                                  fontSize: 12,
                                  fontFamily: 'Source Han Sans',
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                
                // 右侧按钮
                Row(
                  children: [
                    // 喜欢按钮
                    Container(
                      width: 36,
                      height: 36,
                      child: Icon(
                        Icons.favorite,
                        color: const Color(0xFFF73E3B), // paint_7:1628
                        size: 24,
                      ),
                    ),
                    // 评论按钮
                    Container(
                      width: 36,
                      height: 36,
                      child: Icon(
                        Icons.chat_bubble,
                        color: const Color(0xFF67686A), // paint_7:1056
                        size: 24,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          
          // 进度条
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 23, vertical: 16),
            child: Column(
              children: [
                // 进度滑块
                Container(
                  height: 10,
                  child: SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      activeTrackColor: const Color(0xFF000000), // paint_7:052
                      inactiveTrackColor: const Color(0xFF000000).withOpacity(0.3),
                      thumbColor: const Color(0xFF000000), // paint_7:052
                      thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 5),
                      trackHeight: 1,
                    ),
                    child: Slider(
                      value: musicProvider.currentPosition.inSeconds.toDouble(),
                      max: musicProvider.totalDuration.inSeconds.toDouble(),
                      onChanged: (value) {
                        musicProvider.seekTo(Duration(seconds: value.toInt()));
                      },
                    ),
                  ),
                ),
                
                const SizedBox(height: 16),
                
                // 时间信息
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      _formatDuration(musicProvider.currentPosition),
                      style: TextStyle(
                        color: const Color(0xFF3D3D3D), // paint_7:00
                        fontSize: 10,
                        fontFamily: 'Source Han Sans',
                      ),
                    ),
                    Text(
                      '标准',
                      style: TextStyle(
                        color: const Color(0xFF3D3D3D), // paint_7:00
                        fontSize: 10,
                        fontFamily: 'Source Han Sans',
                      ),
                    ),
                    Text(
                      _formatDuration(musicProvider.totalDuration),
                      style: TextStyle(
                        color: const Color(0xFF3D3D3D), // paint_7:00
                        fontSize: 10,
                        fontFamily: 'Source Han Sans',
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 控制按钮区域
  Widget _buildControlButtons(MusicProvider musicProvider) {
    return Container(
      height: 72,
      margin: const EdgeInsets.symmetric(horizontal: 0), // 移除左右间距
      decoration: BoxDecoration(
        color: const Color.fromRGBO(255, 255, 255, 0.8), // paint_7:4191
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          // 循环模式
          IconButton(
            onPressed: () {
              // TODO: 切换循环模式
            },
            icon: Icon(
              Icons.repeat,
              color: const Color(0xFFA6A6A6), // paint_7:1197
              size: 24,
            ),
          ),
          
          // 上一首
          IconButton(
            onPressed: () {
              musicProvider.previousSong();
            },
            icon: Icon(
              Icons.skip_previous,
              color: const Color(0xFF000000), // paint_7:190
              size: 24,
            ),
          ),
          
          // 播放/暂停按钮 (大一些)
          Container(
            width: 48,
            height: 48,
            child: IconButton(
              onPressed: () {
                musicProvider.togglePlayPause();
              },
              icon: Icon(
                musicProvider.isPlaying ? Icons.pause : Icons.play_arrow,
                color: const Color(0xFF000000), // paint_7:190
                size: 36,
              ),
            ),
          ),
          
          // 下一首
          IconButton(
            onPressed: () {
              musicProvider.nextSong();
            },
            icon: Icon(
              Icons.skip_next,
              color: const Color(0xFF000000), // paint_7:190
              size: 24,
            ),
          ),
          
          // 播放列表
          IconButton(
            onPressed: () {
              // TODO: 打开播放列表
            },
            icon: Icon(
              Icons.playlist_play,
              color: const Color(0xFFA6A6A6), // paint_7:1201
              size: 24,
            ),
          ),
        ],
      ),
    );
  }

  // 底部工具栏
  Widget _buildBottomToolbar() {
    return Container(
      height: 72 + MediaQuery.of(context).padding.bottom,
      decoration: BoxDecoration(
        color: const Color.fromRGBO(255, 255, 255, 0.8), // paint_7:4191
      ),
      child: Padding(
        padding: EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            // 手机投屏
            _buildBottomToolItem(Icons.smartphone, const Color(0xFFA6A6A6)),
            
            // 灵感
            _buildBottomToolItem(Icons.lightbulb, const Color(0xFFA6A6A6)),
            
            // 下载
            _buildBottomToolItem(Icons.download, const Color(0xFFA6A6A6)),
            
            // 更多
            _buildBottomToolItem(Icons.more_horiz, const Color(0xFFA6A6A6)),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomToolItem(IconData icon, Color color) {
    return Container(
      width: 50,
      height: 50,
      alignment: Alignment.center,
      child: Icon(
        icon,
        color: color,
        size: 24,
      ),
    );
  }

  // 智能歌手名称组件
  Widget _buildArtistName(String artistName) {
    // 设定一个合理的最大宽度（基于屏幕宽度的40%）
    final screenWidth = MediaQuery.of(context).size.width;
    final maxArtistWidth = screenWidth * 0.4; // 最多占用40%的屏幕宽度
    
    // 测量文本宽度
    final textPainter = TextPainter(
      text: TextSpan(
        text: artistName,
        style: const TextStyle(
          fontSize: 12,
          fontFamily: 'Source Han Sans',
          fontWeight: FontWeight.bold,
        ),
      ),
      maxLines: 1,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout();
    
    final textWidth = textPainter.size.width;
    final needsTruncation = textWidth > maxArtistWidth;
    
    return GestureDetector(
      onTap: needsTruncation ? () => _showFullArtistName(artistName) : null,
      child: Container(
        constraints: BoxConstraints(maxWidth: maxArtistWidth),
        child: Text(
          artistName,
          style: TextStyle(
            color: const Color(0xFF3D3D3D),
            fontSize: 12,
            fontFamily: 'Source Han Sans',
            fontWeight: FontWeight.bold,
            // 添加下划线提示可点击（仅在需要截断时）
            decoration: needsTruncation ? TextDecoration.underline : null,
            decorationColor: needsTruncation ? const Color(0xFF3D3D3D).withOpacity(0.5) : null,
            decorationStyle: needsTruncation ? TextDecorationStyle.dotted : null,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ),
    );
  }

  // 显示完整歌手名称的对话框
  void _showFullArtistName(String artistName) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color.fromRGBO(255, 255, 255, 0.95),
          title: Row(
            children: [
              Icon(
                Icons.person,
                color: const Color(0xFF3D3D3D),
                size: 20,
              ),
              const SizedBox(width: 8),
              const Text(
                '歌手信息',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF3D3D3D),
                  fontFamily: 'Source Han Sans',
                ),
              ),
            ],
          ),
          content: Container(
            constraints: const BoxConstraints(
              minWidth: 200,
              maxWidth: 300,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '完整歌手名称：',
                  style: TextStyle(
                    fontSize: 12,
                    color: Color(0xFF67686A),
                    fontFamily: 'Source Han Sans',
                  ),
                ),
                const SizedBox(height: 8),
                SelectableText(
                  artistName,
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: 'Source Han Sans',
                    color: Color(0xFF3D3D3D),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              style: TextButton.styleFrom(
                foregroundColor: const Color(0xFF3D3D3D),
                padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
              ),
              child: const Text(
                '确定',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontFamily: 'Source Han Sans',
                ),
              ),
            ),
          ],
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          actionsPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        );
      },
    );
  }

  // 格式化时间显示
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return '$minutes:$seconds';
  }
} 